package com.jdk.demo.thread.exchanger;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;

public class ExchangerRunnable implements Runnable{

    Exchanger<String> exchanger = null;
    String    object    = null;
    CountDownLatch begin    = null;

    public ExchangerRunnable(Exchanger<String> exchanger, String object, CountDownLatch begin) {
        this.exchanger = exchanger;
        this.object = object;
        this.begin = begin;
    }

    public void run() {
        try {
        	String previous = this.object;
            if(begin != null){
            	begin.await();
            }
            this.object = this.exchanger.exchange(this.object);
            System.out.println(Thread.currentThread().getName() + " exchanged " + previous + " for " + this.object);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}